//
//  CustomPickerView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/22.
//

import SwiftUI

struct CustomPickerConfig {
    var title: String
    var components: DatePickerComponents
   /* var height: CGFloat
    var backgroundColor: Color
    var buttonText: String */
    init(
        title: String = "请选择时间",
        components: DatePickerComponents = [.hourAndMinute]
      /*  height: CGFloat = 300,
        backgroundColor: Color = Color(hex: "#1E1E1E"),
        buttonText: String = "确定" */
    ) {
        self.title = title
        self.components = components
        /*   self.height = height
        self.backgroundColor = backgroundColor
        self.buttonText = buttonText */
    }
}

struct CustomPickerView: View {
    @Binding var isPresented: Bool
    @Binding var selectedDate: Date
    @State private var tempSelectedDate: Date
    var config: CustomPickerConfig
    init(isPresented: Binding<Bool>, selectedDate: Binding<Date>, config: CustomPickerConfig) {
            self._isPresented = isPresented
            self._selectedDate = selectedDate
            self._tempSelectedDate = State(initialValue: selectedDate.wrappedValue)
            self.config = config
        }
    var body: some View {
        VStack {
            HStack (spacing: 12) {
                Button("取消") {
                    isPresented = false
                }
                .font(.system(size: 16))
                .foregroundStyle(.white)
                Spacer()
                Text(config.title).font(.system(size: 16)).foregroundStyle(.white)
                Spacer()
                Button("确定") {
                    isPresented = false
                    selectedDate = tempSelectedDate
                }
                .font(.system(size: 16))
                .foregroundStyle(.white)
            }
            .padding(.horizontal,20)
            Spacer().frame(height: 28)
            DatePicker(
                "", 
                selection: $tempSelectedDate,
                displayedComponents: config.components
            )
            .environment(\.locale, Locale(identifier: "zh_CN"))
            .datePickerStyle(.wheel)
            .labelsHidden()
            .cornerRadius(10)
            .font(.system(size: 20))
            .environment(\.colorScheme, .dark)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color(hex: "#1E1E1E"))
    }
}

extension View {
    func CustomPickerSheet(
        isPresented: Binding<Bool>,
        selectedDate: Binding<Date>,
        config: CustomPickerConfig = CustomPickerConfig()
    ) -> some View {
        self.sheet(isPresented: isPresented) {
            CustomPickerView(
                isPresented: isPresented,
                selectedDate: selectedDate,
                config: config
            )
            .presentationDetents([.height(300)])
        }
    }
}
